package cn.aihongbo.test.shake

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Looper
import android.util.Log
import kotlin.math.sqrt

/**
 * Created by ZhaoHongBo on 2025/11/4.
 * Copyright (c) 2025 ZHB. All rights reserved.
 */
class HShakeDetector(context: Context) {
    private var sensorManage: SensorManager? =
        context.getSystemService(Context.SENSOR_SERVICE) as SensorManager?
    private var accelerometer: Sensor? = sensorManage?.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
    var listener: (() -> Unit)? = null
    private var lastShakeTime = 0L
    private val SHAKE_INTERVAL_MS = 1000

    private val sensorEventListener = object : SensorEventListener {
        override fun onAccuracyChanged(p0: Sensor?, p1: Int) {
        }

        override fun onSensorChanged(event: SensorEvent?) {
            if (event?.sensor?.type == Sensor.TYPE_ACCELEROMETER) {
                val x: Float = event.values[0] //左右方向
                val y: Float = event.values[1] //前后方向
                val z: Float = event.values[2] //上下方向

//                Log.i("HShakeDetector", "X: $x, Y:$y, Z:$z")

                val g = sqrt(x * x + y * y + z * z) - SensorManager.GRAVITY_EARTH
                val threshold = 60.5 //动态阈值可根据设置调整

                if (g > threshold) {
                    val now: Long = System.currentTimeMillis()
                    if (now - lastShakeTime > SHAKE_INTERVAL_MS) {
                        lastShakeTime = now
                        notifyShakeDetected()
                    }
                }
            }
        }
    }

    fun start() {
        if (accelerometer != null && listener != null) {
            sensorManage?.registerListener(
                sensorEventListener, accelerometer, SensorManager.SENSOR_DELAY_UI
            )
        }
    }

    fun stop() {
        sensorManage?.unregisterListener(sensorEventListener)
    }

    private fun notifyShakeDetected() {
        if (listener != null) {
            val mainHandler = android.os.Handler(Looper.getMainLooper())
            mainHandler.post { listener?.invoke() }
        }
    }
}